import { getLyric, checkMusic, getMusicUrl } from '@/api/song.js'
// import { Base64 } from 'js-base64'

// 处理 musicData.singer 数组，使其变为一个字符串
export function filterSinger(singer) {
  let result = []

  if (!singer) {
    return ''
  }

  singer.forEach((item) => {
    result.push(item.name)
  })
  console.log(result)
  return result.join('/')
}
export function isArrayFn (o) {
  return Object.prototype.toString.call(o) === '[object Array]'
}
export class SingerSong {
  constructor({id, singer, name, album, img}) {
    this.id = id
    this.singer = singer
    this.name = name
    this.album = album
    this.img = img
  }
  // 获取歌词数据
  getLyric() {
    if (this.lyric) {
      return Promise.resolve(this.lyric)
    }
    return new Promise((resolve, reject) => {
      getLyric(this.id).then((res) => {
        if (res.code === 200) {
          this.lyric = res.lrc.lyric
          // this.lyric = Base64.decode(res.lyric)
          resolve(this.lyric)
        } else {
          reject('no lyric')
        }
      })
    })
  }
  // 获取歌曲数据
  checkMusic() {
    if (this.isAvailable) {
      return Promise.resolve(this.isAvailable)
    }
    return new Promise((resolve, reject) => {
      checkMusic(this.id).then((res) => {
        if (res === undefined) {
          reject('亲爱的,暂无版权')
        }
        console.log(res)
        if (res.success === true) {
          this.isAvailable = true
          resolve(this.isAvailable)
        } else {
          this.isAvailable = false
          reject('亲爱的,暂无版权')
        }
      })
    })
  }
  // 获取歌曲url
  getMusicUrl() {
    if (this.url) {
      return Promise.resolve(this.url)
    }
    return new Promise((resolve, reject) => {
      getMusicUrl(this.id).then((res) => {
        if (res.code === 200) {
          this.url = res.data[0].url
          resolve(this.url)
        } else {
          reject('no url')
        }
      })
    })
  }
}

export function createSingerSong(musicData) {
  console.log(musicData.al.length)
  let picUrl = ''
  if (isArrayFn(musicData.al)) {
    picUrl = musicData.al[0].img1v1Url
  } else {
    picUrl = musicData.al.picUrl
  }
  return new SingerSong({
    id: musicData.id,
    singer: filterSinger(musicData.ar),
    name: musicData.name,
    album: '',
    img: picUrl,
    duration: 0
  })
}
